package com.wenzi.rule.verification.spel;

import com.wenzi.rule.verification.base.RuleConfig;
import com.wenzi.rule.verification.exception.RuleValidException;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.util.StringUtils;

public class SpelRule implements Rule{
    private Expression condition;
    private Expression verification;
    private Expression message;

    private RuleConfig ruleConfig;

    public SpelRule(RuleConfig ruleConfig) {
        this.ruleConfig = ruleConfig;
        if(!StringUtils.isEmpty(ruleConfig.getVerification())){
            ExpressionParser parser = new SpelExpressionParser();
            verification = parser.parseExpression(ruleConfig.getVerification());
            message = parser.parseExpression(ruleConfig.getMessage());
            if (!StringUtils.isEmpty(ruleConfig.getCondition())){
                condition = parser.parseExpression(ruleConfig.getCondition());
            }
        }

    }

    @Override
    public void doRule(EvaluationContext context) {
        if(verification != null){
            if (condition != null && !condition.getValue(context,Boolean.class)){
                return;
            }else{
                if (!verification.getValue(context,Boolean.class)){
                    //抛异常
                    throw new RuleValidException(message.getValue(context,String.class));
                }
            }
        }
    }
}
